// pages/addTask/addTask.js

const http = require("./../../utils/http.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canPost:true,
    id:'',
    textContent:'',
    theme:'',
    nowContent:'',
    classfy:'post'
  },

  /** 提交 */
  addTask: function () {
    this.setData({ canPost:false})
    let content = this.data.textContent;
    let theme = this.data.theme;
    let currentDate = new Date().toISOString().substring(0, 10);
    let id = this.data.id;


    if(content == '' && theme == ''){
      wx.showLoading({
        title: '内容不能为空！',
      });
      this.setData({ canPost: true })
      setTimeout(function(){
        wx.hideLoading();
      },1500)
      return false;
    }

    wx.showLoading({
      title: '新增中..'
    });

    console.log(this.data.classfy)

    if(this.data.classfy == 'post') {
      http.post('http://127.0.0.1/tasks', {
      content: content,
      theme: theme,
      userId: 'Taylor',
      time: currentDate
      }, res => {
        this.setData({ canPost: true })
        wx.hideLoading();
        console.log(res.data);
        if(res.data.flag == true){
        // app.globalData.reloadHome = true;
          wx.navigateBack({ comeBack: true });
        }else{
          wx.showToast({
            title: res.data.message,
            icon:'none'
          });
          setTimeout(function () {
            wx.hideLoading();
          }, 1500)
        }
      });
    }

    if(this.data.classfy == 'put') {
      http.put('http://127.0.0.1/tasks', {
      id: id,
      content: content,
      theme: theme,
      userId: 'Taylor',
      time: currentDate
      }, res => {
        this.setData({ canPost: true })
        wx.hideLoading();
        console.log(res.data);
        if(res.data.flag == true){
        // app.globalData.reloadHome = true;
          wx.navigateBack({ comeBack: true });
        }else{
          setTimeout(function () {
            wx.hideLoading();
          }, 1500)
        }
      });
    }
    

  },

  getTheme(evt){
    this.setData({
        theme: evt.detail.value
    })
  },

  getTextContent(evt){
    this.setData({
      textContent: evt.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.id != undefined){
      this.setData({
        id: options.id,
        textContent: options.content,
        theme: options.theme,
        classfy: options.classfy
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})